# -*- coding: utf-8 -*-


import time
import math
import re

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models
from datetime import datetime


class k8sNamespaces(models.Model):
    _name = 'ops_namespaces'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'命名空间', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')


class k8sPod(models.Model):
    _name = 'ops_pod'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'POD容器', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    namespaces = fields.Many2one('ops_namespaces', u'命名空间', track_visibility='onchange')
    prot = fields.Integer(u'POD端口', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')


class container(models.Model):
    _name = 'ops_container'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'容器名称', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    prot = fields.Integer(u'容器端口', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')



class resource(models.Model):
    _name = 'ops_resource'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'名称', track_visibility='onchange')
    esxi_id = fields.Integer(u'关联ID', track_visibility='onchange')
    os_id = fields.Integer(u'关联ID', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    ip = fields.Char(u'IP地址', track_visibility='onchange')
    memory = fields.Char(u'内存', track_visibility='onchange')
    cpu = fields.Char(u'CPU型号', track_visibility='onchange')
    disk = fields.Char(u'磁盘', track_visibility='onchange')
    env_type = fields.Selection([('office', u'办公室'),
                            ('bs', u'宝山机房'),
                            ('aliyun', u'阿里云')], u'机房地址', default='office')
    system_type = fields.Selection([('linux', u'Linux'),
                                    ('windows', u'windows')], u'操作系统类型（linux/win）', default='linux')
    route_ip = fields.Char(u'路由IP', track_visibility='onchange')
    route_prot = fields.Integer(u'路由端口', track_visibility='onchange')
    user = fields.Char(u'账号', track_visibility='onchange')
    protocol = fields.Selection([('ssh', u'ssh'),
                                ('rdp', u'rpd')], u'协议类型（ssh/rdp/telnet）', default='ssh')
    protocol_port = fields.Integer(u'协议端口', track_visibility='onchange')
    authentication_type = fields.Selection([('pw', u'pw'),
                                        ('key', u'key')], u'认证类型（no/pw/key）', default='pw')
    password = fields.Char(u'密码或私钥', track_visibility='onchange')
    user_prompt = fields.Char(u'账号提示（仅telnet）', track_visibility='onchange')
    passwd_prompt = fields.Char(u'密码提示（仅telnet）', track_visibility='onchange')
    group = fields.Char(u'分组', track_visibility='onchange')
    desc = fields.Char(u'描述', track_visibility='onchange')
    use_memory = fields.Char(u'内存使用状态', track_visibility='onchange')
    use_cpu = fields.Char(u'CPU使用状态', track_visibility='onchange')
    use_disk = fields.Char(u'磁盘使用状态', track_visibility='onchange')
    price = fields.Char(u'价格', track_visibility='onchange')
    buy_date = fields.Date(u'购买日期', default=datetime.today().strftime('%Y-%m-%d'), track_visibility='onchange')
    off_date = fields.Date(u'下架日期', default=datetime.today().strftime('%Y-%m-%d'), track_visibility='onchange')
    use_date = fields.Char(u'使用时长', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')


class walle(models.Model):
    _name = 'ops_walle'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'项目环境', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    env_type = fields.Selection([('uat', u'测试环境'),
                            ('pre', u'预发布环境'),
                            ('prd', u'生产环境')], u'项目环境（no/pw/key）', default='uat')
    group = fields.Char(u'项目组名', track_visibility='onchange')
    model = fields.Char(u'模块名称', track_visibility='onchange')
    git = fields.Char(u'仓库地址', track_visibility='onchange')
    domain = fields.Char(u'访问域名', track_visibility='onchange')
    deploy = fields.Char(u'代码检出仓库', track_visibility='onchange')
    exclude = fields.Char(u'排除文件', track_visibility='onchange')
    user = fields.Char(u'用户', track_visibility='onchange')
    webroot = fields.Char(u'webroot', track_visibility='onchange')
    release = fields.Char(u'发布版本库', track_visibility='onchange')
    reserved = fields.Char(u'版本保留数', track_visibility='onchange')
    ip_list = fields.Text(u'机器列表', track_visibility='onchange')
    # 在部署代码之前的准备工作，如git的一些前置检查、vendor的安装（更新），一行一条
    pre_deploy = fields.Text(u'准备工作', track_visibility='onchange')
    # git代码检出之后，可能做一些调整处理，如vendor拷贝，环境适配（mv config - test.php  config.php），一行一条
    post_deploy = fields.Text(u'环境适配', track_visibility='onchange')
    # 同步完所有目标机器之后，更改版本软链之前触发任务。java可能要做一些暂停服务的操作(双引号将会被转义为\")
    pre_release = fields.Text(u'触发任务', track_visibility='onchange')
    # 所有目标机器都部署完毕之后，做一些清理工作，如删除缓存、平滑重载 / 重启服务（nginx、php、task），一行一条(双引号将会被转义为\")
    post_release = fields.Text(u'清理工作', track_visibility='onchange')
    # 按顺序在每台目标机执行高级任务，每台服务器执行完毕后暂停x秒。 默认设置为 0，应用服务使用平滑重载，仅当应用服务无法支持平滑重载必须重启时才配置此参数。
    # 设置为大于 0的值会出现代码发布阶段各个服务器业务代码逻辑不一致的情况，请谨慎配置
    post_release_delay = fields.Text(u'平滑重载', track_visibility='onchange')
    branch = fields.Selection([('branch', u'branch'),
                               ('tag', u'tag')], u'分支/tag上线', default='branch')
    review = fields.Selection([('yes', u'yes'),
                               ('no', u'no')], u'是否开启审核', default='no')
    ansible = fields.Selection([('yes', u'yes'),
                               ('no', u'no')], u'是否开启Ansible', default='no')
    active = fields.Selection([('yes', '0'),
                               ('no', '1')], u'是否启用', default='yes')
    note = fields.Char(u'备注', track_visibility='onchange')
#

class opsUser(models.Model):
    _name = 'ops_user'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'账号', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')


class supplier(models.Model):
    _name = 'ops_supplier'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'供应商名称', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    contact = fields.Char(u'联系人', track_visibility='onchange')
    phone = fields.Char(u'手机号码', track_visibility='onchange')
    note = fields.Text(u'备注', track_visibility='onchange')


class script(models.Model):
    _name = 'ops_script'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'脚本相关', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    des_desc = fields.Text(u'脚本内容', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')


class iptables(models.Model):
    _name = 'ops_iptables'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'端口描述', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    prot = fields.Text(u'端口', track_visibility='onchange')
    type = fields.Selection([('in', 'in'),
                             ('out', 'out')], u'端口规则', default='port')
    note = fields.Char(u'备注', track_visibility='onchange')


class package(models.Model):
    _name = 'ops_package'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'名称', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    package = fields.Text(u'软件包', track_visibility='onchange')
    note = fields.Char(u'备注', track_visibility='onchange')


class monitor(models.Model):
    _name = 'ops_monitor'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'名称', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    type = fields.Selection([('port', u'端口'),
                             ('process', u'进程'),
                             ('pro_resource', u'进程资源'),
                             ('base', u'基础资源')], u'监控类型', default='port')
    note = fields.Text(u'监控描述', track_visibility='onchange')


class proName(models.Model):
    _name = 'ops_proname'
    _order = 'id desc'
    _inherit = ['mail.thread']

    name = fields.Char(u'资源所属组', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    principal = fields.Char(u'资源所属人', track_visibility='onchange')
    note = fields.Text(u'备注', track_visibility='onchange')


class virtualization(models.Model):
    _name = 'ops_virtualization'
    _order = 'id desc'
    _inherit = ['mail.thread']
    
    name = fields.Char(u'系统使用类型', track_visibility='onchange')
    res_id = fields.Integer(u'关联ID', track_visibility='onchange')
    note = fields.Text(u'备注', track_visibility='onchange')
    

class cmdb(models.Model):
    _name = 'ops_cmdb'
    _order = 'id desc'
    _rec_name = 'summary'
    _inherit = ['mail.thread']

    summary = fields.Char(u'资源名称', select=True, size=30, track_visibility='onchange')
    name = fields.Char(u'资源名称', track_visibility='onchange')
    asset_Number = fields.Char(u'资产编号', track_visibility='onchange')
    pro_name = fields.One2many('ops_proname', 'res_id', u'主机所属组', track_visibility='onchange')
    supplier = fields.One2many('ops_supplier', 'res_id', u'供应商', track_visibility='onchange')
    package = fields.One2many('ops_package', 'res_id', u'安装软件包', track_visibility='onchange')
    script = fields.One2many('ops_script', 'res_id', u'脚本相关', track_visibility='onchange')
    monitor = fields.One2many('ops_monitor', 'res_id', u'监控相关', track_visibility='onchange')
    iptalbes = fields.One2many('ops_iptables', 'res_id', u'防火墙相关', track_visibility='onchange')
    virtualization = fields.Many2many('ops_virtualization','cmdb_ops_virtualization',string=u'系统使用类型',track_visibility='onchange')
    
    @api.one
    @api.depends('virtualization')
    def _is_get_virt(self):
        if self.id:
            self.env.cr.execute("select O.name from ops_virtualization O,(select ops_cmdb_id,ops_virtualization_id FROM cmdb_ops_virtualization  where ops_cmdb_id= '%d' ) F WHERE F.ops_virtualization_id = O.id"  % (self.id))
            compute = []
            compute = [x[0] for x in self.env.cr.fetchall()]
            # str_compute = '/ '.join(compute)
            self.virt_list = compute
    virt_list = fields.Char(u'系统类型', compute='_is_get_virt', track_visibility='onchange')
    # virt_list = fields.Char(u'系统类型', compute='_is_get_virt', track_visibility='onchange')
    
    
    local_resource = fields.One2many('ops_resource', 'res_id', u'宿主机资源', track_visibility='onchange')
    virtualization_type = fields.One2many('ops_virtualization', 'res_id', u'系统使用类型', track_visibility='onchange')
    esxi = fields.One2many('ops_resource', 'esxi_id', u'EXSI虚拟主机资源', track_visibility='onchange')
    k8s = fields.One2many('ops_pod', 'res_id', u'K8S容器资源', track_visibility='onchange')
    docker = fields.One2many('ops_container', 'res_id', u'Docker容器资源', track_visibility='onchange')
    os = fields.One2many('ops_resource', 'os_id', u'Openstack虚拟主机资源', track_visibility='onchange')
    create_date = fields.Date(u'创建时间', default=datetime.today().strftime('%Y-%m-%d'), track_visibility='onchange')

    def _get_default_project_ids(self):
        default_project_id = self.env.context.get('default_project_id')
        # return [default_project_id] if default_project_id else None
        
    
    @api.model
    @api.returns('self', lambda value: value.id)
    def create(self, vals):
        self.with_context(mail_create_nolog=True)
        res = models.Model.create(self, vals)
        res.summary = "#%s-%s" % (res.id, res.name)
        return res
        
        
        
    #
    #
    # value = fields.Integer()
    # value2 = fields.Float(compute="_value_pc", store=True)
    # @api.depends('value')
    # def _value_pc(self):
    #     self.value2 = float(self.value) / 100